package com.smdp.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

import static com.smdp.utils.RabbitMQConstants.*;

/**
 * RabbitMQ的配置文件。
 * 导入了RabbitMQ服务器地址（虚拟机）、端口、用户名和密码。
 * 创建了用于秒杀提醒定时任务的延迟队列的交换机、队列、绑定，创建了用于审核的队列的交换机、队列、绑定。
 *
 * @author 蔡方珩
 */
@Configuration
public class RabbitMQConfig {

    @Value("${rabbitmq.host}")
    private String host;
    @Value("${rabbitmq.port}")
    private String port;
    @Value("${rabbitmq.username}")
    private String username;
    @Value("${rabbitmq.password}")
    private String password;

    /**
     * 连接配置
     */
    @Bean
    public ConnectionFactory connectionFactory(){
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setHost(host);
        connectionFactory.setPort(Integer.parseInt(port));
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        return connectionFactory;
    }

    /**
     * rabbitAdmin的配置
     */
    @Bean
    public RabbitAdmin rabbitAdmin(CachingConnectionFactory cachingConnectionFactory){
        RabbitAdmin rabbitAdmin = new RabbitAdmin(cachingConnectionFactory);
        rabbitAdmin.setIgnoreDeclarationExceptions(true);
        return rabbitAdmin;
    }

    /**
     * 声明延迟交换机，使用插件提供的"x-delayed-message"类型交换机
     */
    @Bean
    public CustomExchange delayedExchange(){
        HashMap<String, Object> arguments = new HashMap<>();
        //自定义交换机的类型
        arguments.put("x-delayed-type", "direct");
        /*
         * 交换机名
         * 交换机类型
         * 持久化
         * 自动删除
         */
        return new CustomExchange(DELAYED_EXCHANGE,"x-delayed-message",true,false,arguments);
    }

    /**
     * 声明延迟队列
     */
    @Bean
    public Queue delayedQueue(){
        return new Queue(DELAYED_QUEUE);
    }

    /**
     * 延迟交换机和队列绑定
     */
    @Bean
    public Binding delayedQueueBindingDelayedExchange(){
        return BindingBuilder.bind(delayedQueue()).to(delayedExchange()).with(DELAYED_ROUTE_KEY).noargs();
    }

    /**
     * 声明审核交换机
     */
    @Bean
    public DirectExchange verifyExchange(){
        /*
         * 交换机名
         * 持久化
         * 自动删除
         */
        return new DirectExchange(VERIFY_EXCHANGE,true,false);
    }

    /**
     * 声明延迟队列
     */
    @Bean
    public Queue verifyQueue(){
        return new Queue(VERIFY_QUEUE);
    }

    /**
     * 延迟交换机和队列绑定
     */
    @Bean
    public Binding verifyQueueBindingDelayedExchange(){
        return BindingBuilder.bind(verifyQueue()).to(verifyExchange()).with(VERIFY_ROUTE_KEY);
    }

}
